#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string>
const char *gpipename = "./fifo";
const mode_t mode = 0666;
const int gsize = 1024;
const int gOnlyWrite = O_WRONLY;
const int gOnlyRead = O_RDONLY;

class fifo
{
private:
    void OpenPipe(int flag)
    {
        _fd = ::open(gpipename, flag);
        if (_fd < 0)
        {
            std::cerr << "Open Error" << std::endl;
        }
    }

public:
    fifo() : _fd(-1)
    {
        ::umask(0);
        // 创建命名管道
        int n = mkfifo(gpipename, mode);
        if (n < 0)
        {
            return;
        }
    }
    bool OpenPipeForRead()
    {
         OpenPipe(gOnlyRead);
        if (_fd < 0)
            return false;
        return true;
    }
    bool OpenPipeForWrite()
    {
         OpenPipe(gOnlyWrite);
        if (_fd < 0)
            return false;
        return true;
    }
    int RecePipe(std::string *out)
    {
        char buffer[gsize];
        int n = ::read(_fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
        }
        *out = buffer;
        return n;
    }
    int Wait()
    {
        int i=0;
        int n=::read(_fd,&i,sizeof(i));
        return n;
    }
   void Signal()
    {
        int i=1;
        int n=::write(_fd,&i,sizeof(i));
        if(n<0) std::cerr<<"write error"<<std::endl;
    }
    ~fifo()
    {
        if (_fd >= 0)
            ::close(_fd);
        int n = ::unlink(gpipename);
        if (n < 0)
        {
            std::cout << "unlink failed..." << std::endl;
            return;
        }
        std::cout << "unlink success..." << std::endl;
    }

private:
    int _fd;
};
fifo f;
